package servlet;

import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月02日11:21
 */
@WebServlet("/modifyEmp")
public class ModifyEmp extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String id=request.getParameter("id");
        String name=request.getParameter("name");
        System.out.println(name);
        String salary=request.getParameter("salary");
        String gender=request.getParameter("gender");
        String edu=request.getParameter("edu");
        String[] hobbies=request.getParameterValues("hobbies");

        Connection conn=null;
        PreparedStatement ps=null;
        String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set name=?,salary=?,gender=?,edu=?,hobbies=? ")
                    .append(" where id=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            //执行DML操作
            ps.executeUpdate();

            response.sendRedirect("findAll");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭释放资源
        }
    }
}

